#!/bin/bash -eu
#
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

source /opt/c2d/c2d-utils || exit 1

# Read passwords generated for current instance:
declare -r mysql_redmineuser_password="$(get_attribute_value "mysql-redmineuser-password")"
declare -r redmine_admin_password="$(get_attribute_value "redmine-admin-password")"

# Update Redmine's dedicated user password.
mysql -u root -e "SET PASSWORD FOR 'redmineuser'@'localhost' = PASSWORD('${mysql_redmineuser_password}')"

cd /opt/redmine

# Replace auto-generated password for Redmine's MySQL user:
sed -i "s/password: temp/password: ${mysql_redmineuser_password}/g" config/database.yml

export RAILS_ENV=production

# Temporay disable error handling for suppress errors from ruby
set +eu \
  && source /usr/local/rvm/scripts/rvm \
  && set -eu

mkdir -p /tmp && chown -R redmine:redmine tmp/

# Replace default password for Redmine admin user:
bin/rails runner "user = User.find_by_login('admin') ; user.password, user.password_confirmation = '${redmine_admin_password}'; user.save!" -e production
